package com.starlight.ts_clouddev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.starlight.ts_clouddev.infrastructure.entity.CloudUser;
import com.starlight.ts_clouddev.infrastructure.mapper.CloudUserMapper;
import com.starlight.ts_clouddev.service.CloudUserService;
import com.starlight.ts_clouddev.util.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
* @author yfy2001
* @description 针对表【cloud_user】的数据库操作Service实现
* @createDate 2023-05-18 15:09:14
*/
@Service
public class CloudUserServiceImpl extends ServiceImpl<CloudUserMapper, CloudUser>
    implements CloudUserService{

    @Resource
    private CloudUserMapper cloudUserMapper;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public String userLogin(CloudUser cloudUser) {
//        System.out.println(cloudUser.toString());
        CloudUser loginUser=cloudUserMapper.selectOne(new LambdaQueryWrapper<CloudUser>()
                .eq(CloudUser::getEmail,cloudUser.getEmail()));
        if (loginUser==null){
            throw new RuntimeException("用户名或密码错误！");
        }
        //密码加密后判断是否相同
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(cloudUser.getPassword(),loginUser.getPassword())){
            throw new RuntimeException("用户名或密码错误！");
        }
        System.out.println("登录用户id:"+loginUser.getId());
        return jwtUtils.generateToken(loginUser);
    }

    @Override
    public String logout(String token) {
        redisTemplate.delete(token);
        return "退出成功";
    }

    @Override
    public Integer userRegister(CloudUser cloudUser) {
        boolean exists=cloudUserMapper.exists(new LambdaQueryWrapper<CloudUser>()
                .eq(CloudUser::getPassword,cloudUser.getEmail()));
        if (exists){
            throw new RuntimeException("用户名已经存在！");
        }
        return cloudUserMapper.insert(cloudUser);
    }
}




